<script setup lang="ts">
import {InfoCircleOutlined} from "@ant-design/icons-vue";
import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message} from "ant-design-vue";
import LineTextArea from "~/contentScripts/views/wxt/components/LineTextArea.vue";
import {WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";

const props = defineProps({
  value: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  products: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  plans: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
});

const emit = defineEmits([
  "update:value",
]);
const data = reactive({
  switchValue: true,
  titleMustIncludeKeyword: false,
  keywordIncludeText: '',
  allKeywordNotRepeat: false,
  keywordNotIncludeText: '',
});
const dataSource = ref<any[]>([]);
const columns = [
  {
    title: '商品标题',
    dataIndex: 'title',
    dataType: 'custom',
    slot: 'title',
  },
  {
    title: '计划名称',
    dataIndex: 'plan.campaignName',
    width: 160,
    // dataType: 'custom',
    // slot: 'planName',
  },
  {
    title: '关键词数量',
    dataIndex: 'keywordCount',
    width: 160,
    dataType: 'custom',
    slot: 'keywordCount',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 80,
    dataType: 'custom',
    slot: 'action',
  },
]
const choseProductColumns = [
  {
    title: '商品标题',
    dataIndex: 'item.title',
    width: 240,
    dataType: 'custom',
    slot: 'title',
  },
]
const visible = ref(false);
const current = ref(0);
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
const inputKeywords = ref('');
const selectedRows = ref<any[]>([]);
const addKeywords = () => {
  // 判断是否勾选商品
  if (selectedRows.value.length == 0) {
    message.error('请勾选商品');
    return;
  }
  // 判断是否输入关键词
  if (!inputKeywords.value.replaceAll("\n", "").replace(/\s+/g, "")) {
    message.error('请输入关键词');
    return;
  }
  // 根据选中的selectedRows商品添加关键词
  let dd: any[] = [];
  selectedRows.value.forEach((item: { title: string | any[]; }) => {
    let keywords = inputKeywords.value.split('\n');
    // 判断标题是否包含关键字
    if (data.titleMustIncludeKeyword) {
      keywords = keywords.filter((keyword: string) => item.title.includes(keyword));
    }
    // 关键词包含文本
    if (data.keywordIncludeText) {
      const texts = data.keywordIncludeText.split(' ');
      keywords = keywords.filter((keyword: string) => texts.includes(keyword));
    }
    // 关键词不包含文本
    if (data.keywordNotIncludeText) {
      const texts = data.keywordIncludeText.split(' ');
      keywords = keywords.filter((keyword) => !texts.includes(keyword));
    }
    dd.push({
      item: item,
      keywords: keywords,
    })
  })
  // 处理dd 的数据 如果 allKeywordNotRepeat 为true 则去重
  if (data.allKeywordNotRepeat) {
    dd.forEach((item) => {
      item.keywords = Array.from(new Set(item.keywords));
    })
  }
  // 把dd数据添加到dataSource中 如果item的itemId相同则合并keywords 并且去重
  dd.forEach((item) => {
    props.plans.forEach((plan) => {
      const index = dataSource.value.findIndex((d) => d.item.itemId == item.item.itemId && d.plan.campaignId == plan.campaignId);
      if (index > -1) {
        dataSource.value[index].keywords = Array.from(new Set(dataSource.value[index].keywords.concat(item.keywords)));
      } else {
        dataSource.value.push({
          item: typeof item.material === 'undefined' ? item.item : {itemId: item.material.materialId, ...item.material},
          plan: plan,
          keywords: item.keywords,
        })
      }
    })
  })
  console.log(dataSource.value);
  visible.value = false;
  message.success('添加成功');
}
const remove = (row: any) => {
  const index = dataSource.value.findIndex((item) => item.item.itemId == row.item.itemId && item.plan.campaignId == row.plan.campaignId);
  if (index > -1) {
    dataSource.value.splice(index, 1);
  }
}
const clear = (row: any) => {
  const index = dataSource.value.findIndex((item) => item.item.itemId == row.item.itemId && item.plan.campaignId == row.plan.campaignId);
  if (index > -1) {
    dataSource.value[index].keywords = [];
  }
}
watch(() => dataSource.value, (val) => {
  // 整理数据为格式 {campaignId:{itemId:[keywords]}};
  const d: any = {};
  // console.log(dataSource.value);
  val.forEach((item) => {
    if (typeof item.plan.adgroupId !== 'undefined') {
      if (!d[item.plan.campaignId]) {
        d[item.plan.campaignId] = {};
      }
      d[item.plan.campaignId][item.plan.adgroupId] = item.keywords;
    } else {
      if (!d[item.plan.campaignId]) {
        d[item.plan.campaignId] = {};
      }
      if (!d[item.plan.campaignId][item.item.itemId]) {
        d[item.plan.campaignId][item.item.itemId] = [];
      }
      d[item.plan.campaignId][item.item.itemId] = item.keywords;
    }
  })
  emit('update:value', d);
}, {
  deep: true,
})
const productsData = ref<any[]>(props.products.map((p) => {
  if (typeof p.material === 'undefined') {
    return p;
  } else {
    return {
      ...p.material,
      itemId: p.material.materialId,
    }
  }
}));
watch(() => props.products, (val) => {
  productsData.value = val.map((p) => {
    if (typeof p.material === 'undefined') {
      return p;
    } else {
      return {
        ...p.material,
        itemId: p.material.materialId,
      }
    }
  })
}, {
  deep: true,
})
</script>

<template>
  <div class="box" style="overflow: hidden;">
    <div class="title">
      <a-row>
        <a-col flex="1">

          <span class="bold">手动添加关键词</span>
          <a-tooltip title="批量添加自定义关键词，按设定条件分配到已选择的单元，未设置手动添加的商品会自动添加">
            <InfoCircleOutlined/>
          </a-tooltip>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span class="gray">手动添加关键词: </span>
          <a-switch v-model:checked="data.switchValue" size="small"/>
        </a-col>
        <a-col>
          <a-space>
            <a-button type="primary" size="small" danger @click="()=> selectedRows.map((item)=>remove(item))">批量删除
            </a-button>
            <a-button type="primary" size="small" @click="visible=true">添加关键字</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
    <div class="content" style="height: 403px;">
      <div class="mask" v-if="!data.switchValue">
        <InfoCircleOutlined/>&nbsp;&nbsp;不需要手动添加关键词
      </div>
      <base-table :columns="columns" :data-source="dataSource" table-name="宝贝列表" :scroll="{
        y:323,
      }"
      >
        <template #title="row">
          <a-row type="flex" class="adgroupName" :gutter="5">
            <a-col>
              <a-popover placement="right">
                <template #content>
                  <img :src="row.item.imgUrl"
                       style="width: 200px;height: 200px;"
                  />
                </template>
                <img :src="row.item.imgUrl"
                     style="width: 60px;height: 60px;border-radius: 5px;"
                />
              </a-popover>
            </a-col>
            <a-col flex="1" class="title">
              <a-tooltip :title="row.item.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.item.title }}</span>
              </a-tooltip>
              <div>
                <a-space>
                  <span style="color: #666;">ID: {{ row.item.itemId }}</span>
                  <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;" @click="copy(row.item.itemId)"/>
                </a-space>
              </div>
            </a-col>
          </a-row>
        </template>
        <template #keywordCount="row">
          <a-tooltip :title="row.keywords.join(',')">
            <a-tag color="blue">{{ row.keywords.length }}</a-tag>
          </a-tooltip>
          <a-button type="link" danger size="small" @click="()=> clear(row)">清空</a-button>
        </template>
        <template #action="row">
          <a-button type="link" danger size="small" @click="remove(row)">删除</a-button>
        </template>
      </base-table>
      <wxt-modal title="手动添加关键字" width="90%" :style="{
        top:'revert-layer',
      }" v-model:visible="visible"
      >
        <a-row type="flex" :gutter="10">
          <a-col style="width: 800px;" class="content">
            <a-row type="flex">
              <a-col :span="12">
                <a-row type="flex" align="middle">
                  <a-col :span="11" style="text-align: right;padding-right:10px;">
                    <span>标题必须包括关键词: </span>
                  </a-col>
                  <a-col :span="13">
                    <a-switch v-model:checked="data.titleMustIncludeKeyword" size="small"/>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="12">
                <a-row type="flex" align="middle">
                  <a-col :span="11" style="text-align: right;padding-right:10px;">
                    <span>关键词包含文本: </span>
                  </a-col>
                  <a-col :span="13">
                    <a-input v-model:value="data.keywordIncludeText" size="small" style="width: 100%;"
                             placeholder="多个空格分隔"
                    />
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <a-row type="flex">
              <a-col :span="12">
                <a-row type="flex" align="middle">
                  <a-col :span="11" style="text-align: right;padding-right:10px;">
                    <span>统一商品关键词不重复: </span>
                  </a-col>
                  <a-col :span="13">
                    <a-switch v-model:checked="data.allKeywordNotRepeat" size="small"/>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="12">
                <a-row type="flex" align="middle">
                  <a-col :span="11" style="text-align: right;padding-right:10px;">
                    <span>关键词不包含文本: </span>
                  </a-col>
                  <a-col :span="13">
                    <a-input v-model:value="data.keywordNotIncludeText" size="small" style="width: 100%;"
                             placeholder="多个空格分隔"
                    />
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <a-row style="height: 400px;">
              <LineTextArea v-model:value="inputKeywords" placeholder="请输入关键字，一行一个"/>
            </a-row>
          </a-col>
          <a-col flex="1" style="overflow: hidden;">
            <base-table v-model:selected-rows="selectedRows" row-key="itemId" selection :columns="choseProductColumns"
                        :data-source="productsData" table-name="宝贝列表" :scroll="{
        y:323,
            }"
            >
              <template #toolbar>
                <div style="color: #444;">
                  <span style="color: #ff4d4f;"> * </span>
                  请勾选需要添加关键词的商品
                </div>
              </template>
              <template #title="row">
                <a-row type="flex" class="adgroupName" :gutter="5">
                  <a-col>
                    <a-popover placement="right">
                      <template #content>
                        <img :src="row.imgUrl"
                             style="width: 200px;height: 200px;"
                        />
                      </template>
                      <img :src="row.imgUrl"
                           style="width: 60px;height: 60px;border-radius: 5px;"
                      />
                    </a-popover>
                  </a-col>
                  <a-col flex="1" class="title">
                    <a-tooltip :title="row.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.title }}</span>
                    </a-tooltip>
                    <div>
                      <a-space>
                        <span style="color: #666;">ID: {{ row.itemId }}</span>
                        <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;"
                                      @click="copy(row.itemId)"
                        />
                      </a-space>
                    </div>
                  </a-col>
                </a-row>
              </template>
            </base-table>
          </a-col>
        </a-row>
        <a-divider style="margin: 10px 0"/>
        <a-row type="flex" justify="center">
          <a-space>
            <a-button @click="visible=false">取消</a-button>
            <a-button type="primary" @click="addKeywords">添加</a-button>
          </a-space>
        </a-row>
      </wxt-modal>
    </div>
  </div>
</template>

<style lang="less" scoped>
.box {
  border: #eee solid 1px;
  border-radius: 10px;
  overflow: hidden;

  > .title {
    background-color: #ebeef5;
    padding: 10px;
    line-height: 28px;

    .bold {
      font-weight: bold;
      color: #444;
    }

    .gray {
      color: #555;
    }
  }
}

//

.content {
  color: #222;
  position: relative;

  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, .9);
    color: #ff4d4f;
    //opacity: 0.5;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  > div {
    padding: 10px;
    border-bottom: #eee solid 1px;

    &:last-child {
      border-bottom: none;
    }

    .ant-row {
      height: 30px;
      line-height: 30px;

      .ant-col {
        height: 30px;
        line-height: 30px;
        color: #444;
      }
    }
  }
}

.product {
  .title {
    // 一行超出隐藏
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .hover-show {
    display: none;
  }

  &:hover {
    .hover-show {
      display: block;
    }
  }
}

.top {
  background: rgb(249, 249, 249);
  padding: 10px;
  border-radius: 7px;
  color: #444;
}

.two-line {
  // 文字超出两行省略号
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 42px;
}
</style>
